<?php
namespace App\Http\Controllers;
use App\Form;
use App\Formitem;
use App\Comment;
use App\FY\FeiyuApi;
use App\Keep;
use App\Live;
use App\LiveUser;
use App\Message;
use App\Post;
use App\Postmeta;
use App\ShopCat;
use App\ShopCode;
use App\ShopGoods;
use App\Shopmeta;
use App\ShopOrder;
use App\ShopUser;
use App\Tag;
use App\TagGroup;
use App\Usermeta;
use App\User;
use App\ShopCoupon;
use Validator;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Request;

class AdminController extends Controller
{
    private function CurrentUser(){
        $currentUser = Auth::user();
        $meta = Usermeta::where("user_id",$currentUser->id)->get();
        foreach ($meta as $m){
            $currentUser["$m->key"] = $m->value;
        }
        return $currentUser;
    }
    private function getQR($id,$path,$width=430){
        #$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxfca50078ea0ff5c1&secret=abbf5d3bc574fc27fe7802b6abfa1d0a';
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxfca50078ea0ff5c1&secret=2b9ea75c582a6b7b6be2a40aefea1327';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $json = curl_exec($ch);
        curl_close($ch);
        $json = json_decode($json);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$json->access_token;
        $post_data = array ("path" => $path,"width" => $width);
        $post_data = json_encode($post_data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            file_put_contents("upload/view/$id.jpg", $tmpInfo);
            return asset("upload/view/$id.jpg");
        }
    }
    private function strip_html_tags($tags,$str){
        $html=array();
        foreach ($tags as $tag) {
            $html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
        }
        $data=preg_replace($html, '', $str);
        return $data;
    }
    public function admin()
    {
        $userNum = User::count();
        $comNum = User::where("level",4)->count();
        $one = Tag::where('type','xcx')->where('name','路演')->first();
        $two = Tag::where('type','xcx')->where('name','活动')->first();
        $activeNum = Post::where(function($query) use ($one,$two) {
                $query->where('xcx', $one->id)
                    ->orWhere(function ($query) use ($two) {
                        $query->where('xcx', $two->id);
                    });
            })->count();
        $formNum = Form::count();
        $num =[$userNum,$comNum,$activeNum,$formNum];
        $News = Post::orderBy("view", 'desc')->simplePaginate(10);
        foreach ($News as $n){
            $n->keep = Keep::where("status",1)->where("post_id",$n->id)->count();
        }
        $User = User::orderBy("id", 'desc')->simplePaginate(12);
        foreach ($User as $u){
            $avatar = Usermeta::where("user_id",$u->id)->where("key","avatar")->first();
            $u->avatar = $avatar?$avatar->value:"";
            $u->time = $u->created_at->format('m-d');
        }
//        dd($User);
        return view('admin.admin',[
            "CurrentUser"=>$this->CurrentUser(),
            "num"=>$num,
            "news"=>$News,
            "user"=>$User
        ]);
    }
    private function metaSave($postId,$key,$value,$id,$del=null){
        if($id){
            $Postmeta = Postmeta::find($id);
            if($del){
                $Postmeta->delete();
            }else{
                $Postmeta->value = $value;
                $Postmeta->save();
            }
        }else{
            $Postmeta = new Postmeta();
            $Postmeta->post_id = $postId;
            $Postmeta->key = $key;
            $Postmeta->value = $value;
            $Postmeta->save();
        }
    }
    private function ShopMetaSave($postId,$key,$value,$id,$del=null){
        if($id){
            $Postmeta = Shopmeta::find($id);
            if($del){
                $Postmeta->delete();
            }else{
                $Postmeta->value = $value;
                $Postmeta->save();
            }
        }else{
            $Postmeta = new Shopmeta();
            $Postmeta->shop_id = $postId;
            $Postmeta->key = $key;
            $Postmeta->value = $value;
            $Postmeta->save();
        }
    }
    public function FormItem(){
        $FormItems = Formitem::orderBy('id', 'desc')->paginate(10);
        return view('admin.formitem',[
            'formItems' => $FormItems,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function FormItemSave(Request $request){
        $data = $request->input('FormItem');
//        var_dump($data);
        $value = Array();
        $i = 0;
        while (isset($data['item_'.$i])){
//            array_push($arr,$data['item_'.$i]);
            $arr = Array();
            $arr["type"] = $data['item_'.$i.'_t'];
            $arr["name"] = $data['item_'.$i];
            $arr["placeholder"] = $data['item_'.$i.'_p'];
            array_push($value,$arr);
            $i++;
        }

        if(isset($data['id'])){
            $FormItem = Formitem::find($data['id']);

            $FormItem->name = $data["name"];
            $FormItem->value = json_encode($value, JSON_UNESCAPED_UNICODE);
            if($FormItem->save()){
                return redirect('admin/formitem/edit/'.$data['id'])->with('success','更新成功');
            }else{
                return redirect('admin/formitem/edit/'.$data['id'])->with('fail','更新失败');
            }
        }else{
        $FormItem = new Formitem();

        $FormItem->name = $data["name"];
        $FormItem->value = json_encode($value, JSON_UNESCAPED_UNICODE);
        if($FormItem->save()){
            return redirect('admin/formitem')->with('success','新增成功');
        }else{
            return redirect('admin/formitem')->with('fail','新增失败');
        }
        }
    }
    public function FormItemDel($id){
        $FormItem = Formitem::find($id);
        if($FormItem->delete()){
            return redirect('admin/formitem')->with('success','删除成功');
        }else{
            return redirect('admin/formitem')->with('fail','删除失败');
        }
    }
    public function FormItemEdit($id){
        $FormItem = Formitem::find($id);
        $FormItem->value = json_decode($FormItem->value);
        $typeName = Array("text"=>"文本","textarea"=>"文本框","time"=>"日期","picker"=>"选项","phone"=>"手机验证","min"=>"时间","title"=>"分段标题",);
        foreach ($FormItem->value as $f){
            $f->typeName = $typeName[$f->type];
        }
        return view('admin.formedit',[
            'FormItem' => $FormItem,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Form(Request $request){
        $Input = $request->input();
        $Form = Form::orderBy('id', 'desc');
        $name = null;
        if($request->has('start')&&$request->has('end')){
            $start_date = date('d-m-Y', strtotime($Input["start"]));
            $end_date = date('d-m-Y', strtotime($Input["end"]." +1 day"));
            $str_start_date = date("Y-m-d H:i:s",strtotime($start_date));
            $str_end_date = date("Y-m-d H:i:s",strtotime($end_date));
            $Form = $Form->where('created_at','>=',"$str_start_date")->where('created_at','<=',"$str_end_date");
        }
        if($request->has('id')){
            $Form = $Form->where('parent',$Input["id"])->where('item',$Input["item"]);
            if($request->has('start')&&$request->has('end')){
                $Form = $Form->get();
            }else{
                $Form = $Form->paginate(20);
            }
            if($Input["item"]!=0){
                $name = Formitem::find($Input["item"]);
                $name = json_decode($name->value);
            }else{
                if(count($Form)&&$Form[0]->type==='coupon'){
                    $name = [(object)Array("name"=>"联系人"),(object)Array("name"=>"联系电话"),(object)Array("name"=>"营业执照")];
                }else{
                    $name = [(object)Array("name"=>"联系人"),(object)Array("name"=>"联系电话"),(object)Array("name"=>"公司信息"),(object)Array("name"=>"公司简介")];
                }
            }
        }else{
            if($request->has('type')){
                $Form = $Form->where('type',$Input["type"]);
            }
            if($request->has('start')&&$request->has('end')){
                $Form = $Form->get();
            }else{
                $Form = $Form->paginate(20);
            }
        }
//        dd($Form);
        $TypeName = Array("service"=>"服务预约","active"=>"活动申请","join"=>"活动预约","user"=>"入驻申请","coupon"=>"优惠券申请");
        if($Form){
            foreach ($Form as $f){
                $Post = null;
                if($f->parent!=0){
                    $Post = Post::find($f->parent);
                }
                $f->form = json_decode($f->form);
                $f->title = $f->parent!=0&&$Post?$Post->title:0;
                $f->typeName = $TypeName["$f->type"];
            }
        }
//        dd($Form,$name);
        return view('admin.form',[
            "CurrentUser"=>$this->CurrentUser(),
            "Forms"=>$Form,
            "Name"=>$name
        ]);
    }
    public function FormDel($id){
        $Form = Form::find($id);
        if($Form->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function FormEdit($id){
        $Form = Form::find($id);
        $value = json_decode($Form->form);
        $name = Array();
        if($Form->item){
            $items = Formitem::find($Form->item);
            $item = json_decode($items->value);
            for ($i=0;$i<count($item);$i++){
                if($item[$i]->type === 'title')continue;
                array_push($name,$item[$i]->name);
            }
        }else{
            $name = ["联系人","联系电话","公司信息","公司简介"];
        }
        return view('admin.formview',[
            "CurrentUser"=>$this->CurrentUser(),
            "Form"=>$Form,
            "Value"=>$value,
            "Name"=>$name
        ]);
    }
    public function FormCoupon($id,$status){
        $Form = Form::find($id);
        $Form->status = $status;
        if($Form->save()){
            $Post = Post::find($Form->parent);
            $Message = new Message();
            $Message -> post_user = 1;
            $Message -> status = 0;

            if($status == 2){
                $Message -> content = '你所申请的 '.$Post->title.' 优惠券未被通过';
            }elseif($status == 1){
                $Meta = Postmeta::where("post_id",$Form->parent)->whereIn("key",["coupon_id","coupon_discount","coupon_cash","coupon_cut","coupon_full","startCoupon","endCoupon","coupon_type"])->get();
                $CouponInfo = [];
                foreach ($Meta as $m){
                    $CouponInfo["$m->key"] = $m->value;
                }
                if(isset($CouponInfo["coupon_discount"])){
                    $cat = "discount";
                    $content = $CouponInfo["coupon_discount"];
                }elseif (isset($CouponInfo["coupon_cash"])){
                    $cat = "cash";
                    $content = $CouponInfo["coupon_cash"];
                }else{
                    $cat = "cut";
                    $content = json_encode(Array("full"=>$CouponInfo["coupon_full"],"cut"=>$CouponInfo["coupon_cut"]), JSON_UNESCAPED_UNICODE);
                }
                $Coupon = new ShopCoupon();
                $Coupon->user_id = $Form->user_id;
                $Coupon->post_id = $Form->parent;
                $Coupon->coupon_id = $CouponInfo["coupon_id"];
                $Coupon->startTime = $CouponInfo["startCoupon"];
                $Coupon->endTime  = $CouponInfo["endCoupon"];
                $Coupon->title = $Post->title;
                $Coupon->cat = $cat;
                $Coupon->type = $CouponInfo["coupon_type"];
                $Coupon->content = $content;
                if($Coupon->save()){
                    $meta = Postmeta::where("post_id",$Form->parent)->where("key","coupon_num")->first();
                    $meta->value--;
                    $meta->save();
                }
                $Message -> content = '你所申请的 '.$Post->title.' 优惠券已通过，请在 我的优惠券 里查看';
            }
            $_Msg = Message::where("parent",0)->where(function($query) use ($Form){
                $query->where(function($query) use ($Form){
                    $query->where('get_user', $Form->user_id)->where('post_user', 1);
                })->orWhere(function($query) use ($Form){
                    $query->where('get_user', 1)->where('post_user', $Form->user_id);
                });
            })->first();
            $Message->get_user = $Form->user_id;
            $Message->parent = $_Msg?$_Msg->id:0;
            $Message -> save();
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }

    //评论功能
    public function Comment(){
        $Comments = Comment::orderBy('id', 'desc')->paginate(20);
        foreach ($Comments as $Comment){
            $Post = Post::find($Comment->post_id);
            $Comment->title = $Post?$Post->title:"已删除";
        }
        return view('admin.comment',[
            'Comments' => $Comments,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function CommentDel($id){
        $Comment = Comment::find($id);
        if($Comment->delete()){
            return redirect('admin/comment')->with('success','删除成功');
        }else{
            return redirect('admin/comment')->with('fail','删除失败');
        }
    }

    //展示功能
    public function Tag($type){
        if($type=='service'){
            $tags = Tag::whereIn('type',['service','shop','coupon','couponCat'])->paginate(20);
        }else{
            $tags = Tag::where('type',$type)->paginate(20);
        }
        return view('admin.tag',[
            'Tags' => $tags,
            'type' => $type,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function TagSave(Request $request){
        $data = $request->input('Tag');
//        dd($data);
        if(isset($data['id'])){
            $Tag = Tag::find($data['id']);
            $Tag->filter = $data["filter"];

            $Tag->name = $data["name"];
            if($data["more"]){
                $Tag->more = $data["more"];
            }
            $Tag->order_id = $data["order_id"]?$data["order_id"]:$Tag->id;
            if($Tag->save()){
                $i = 0;
                if(isset($data['f_'.$i])){
                    $t_arr = Tag::where("parent_id",$Tag->id)->get();
                    $arr = [];
                    foreach ($t_arr as $t_a){
                        array_push($arr,$t_a->id);
                    };
                    $num = count($arr);
                    do{
                        if(isset($data['t_'.$i])){
                            $t = Tag::find($data['t_'.$i]);
                            $t->name = $data['f_'.$i];
                            $key = array_search($data['t_'.$i],$arr);
                            if($num&&$key !== false){
                                array_splice($arr, $key,1);
                            }
                        }else{
                            $t = new Tag();
                            $t->type = 'filter';
                            $t->parent_id = $Tag->id;
                            $t->name = $data['f_'.$i];
                        }
                        $t->save();
                        $i++;
                    } while(isset($data['f_'.$i]));
                    if($num = count($arr)){
                        for ($i=0;$i<$num;$i++){
                            $t = Tag::find($arr[$i]);
                            $t->delete();
                        }
                    }
                }
                return redirect()->back()->with('success','更新成功');
            }else{
                return redirect()->back()->with('fail','更新失败');
            }
        }else{
            $Tag = new Tag();

            $Tag->name = $data["name"];
            $Tag->type = $data["type"];
            $Tag->filter = $data["filter"];
            if($data["more"]){
                $Tag->more = $data["more"];
            }

            if($Tag->save()){
                $Tag->order_id = $data["order_id"]?$data["order_id"]:$Tag->id;
                $Tag->save();
                return redirect()->back()->with('success','新增成功');
            }else{
                return redirect()->back()->with('fail','新增失败');
            }
        }

    }
    public function TagEdit($id){
        $Tag = Tag::find($id);
        $arrId = [];
        $arrName = [];
        if($Tag->type=='service'||$Tag->type=='couponCat'){
            $t_arr = Tag::where("parent_id",$Tag->id)->get();
            foreach ($t_arr as $t_a){
                array_push($arrId,$t_a->id);
                array_push($arrName,$t_a->name);
            };
        }
        return view('admin.tagedit',[
            'Tag' => $Tag,
            'ArrId' => $arrId,
            'ArrName' => $arrName,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function TagDel($id){
        $Tag = Tag::find($id);
        if($Tag->type!='xcx'&&$Tag->delete()){
            return redirect('admin/tag/'.$Tag->type)->with('success','删除成功');
        }else{
            return redirect('admin/tag/'.$Tag->type)->with('fail','删除失败');
        }
    }

    //私信功能
    public function Message(){
        $Messages = Message::where("status","<",2)->orderBy('id', 'desc')->paginate(20);
        foreach ($Messages as $item){
            if($item->get_user==0){
                $item->getName = '全部用户';
                $item->postName = '系统公告';
            }else{
                $user = User::find($item->get_user);
                $item->getName = $user?$user->name:"0";
                $user = User::find($item->post_user);
                $item->postName = $user?$user->name:"0";
            }
        }
        return view('admin.message',[
            'Messages' => $Messages,
            'type'=>'all',
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function MessageView($id){
        $Msg = Message::find($id);
        if($Msg->parent != 0){
            $parent = $Msg->parent;
        }else{
            $parent = $id;
        }
        $Messages = Message::where("status","<",2)->whereRaw('parent = ? OR id = ?',[$parent,$parent])->orderBy('id', 'desc')->paginate(20);
        foreach ($Messages as $item){
            if($item->get_user==0){
                $item->getName = '全部用户';
                $item->postName = '系统公告';
            }else{
                $user = User::find($item->get_user);
                $item->getName = $user?$user->name:"0";
                $user = User::find($item->post_user);
                $item->postName = $user?$user->name:"0";
            }
        }
        return view('admin.message',[
            'Messages' => $Messages,
            'type'=>'view',
            'view'=>$id,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function MessageDel($id){
        $Msg= Message::find($id);
        $Msg->status = 2;
        if($Msg->save()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function MessageDelView($id,$view){
        $Msg= Message::find($id);
        $Msg->status=2;
        if($view&&$view==$id){
            if($Msg->parent != 0){
                $parent = $Msg->parent;
            }else{
                $parent = $id;
            }
            $Message = Message::where("status","<",2)->whereRaw('(parent = ? OR id = ?) AND id != ?',[$parent,$parent,$id])->first();
            if($Msg->save()){
                if($Message){
                    return redirect('admin/message/view/'.$Message->id)->with('success','删除成功');
                }else{
                    return redirect('admin/message')->with('success','删除成功');
                }
            }else{
                return redirect()->back()->with('fail','删除失败');
            }
        }
        if($Msg->save()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function MessageAdd(Request $request){
        if($request->has("id")){
            $Message = Message::find($request->input('id'));
        }else{
            $Message = null;
        }
        return view('admin.messageadd',[
            "CurrentUser"=>$this->CurrentUser(),
            "Message"=>$Message
        ]);
    }
    public function MessageSave(Request $request){
        $data = $request->input('Message');
        $type = isset($data['more'])?1:0;

        $Message = new Message();
        $Message -> content = $data['content'];
        $Message -> post_user = 1;
        $Message -> status = 0;

        if(!$type){
            $get_user = $data['get_user'];
            $get_userInfo = User::find($data['get_user']);
            if(!$get_userInfo){
                return redirect()->back()->with('fail','找不到对应用户');
            }
            $_Msg = Message::where("parent",0)->where(function($query) use ($get_user){
                $query->where(function($query) use ($get_user){
                    $query->where('get_user', $get_user)->where('post_user', 1);
                })->orWhere(function($query) use ($get_user){
                    $query->where('get_user', 1)->where('post_user', $get_user);
                });
            })->first();
            $Message->get_user = $get_user;
            $Message->parent = $_Msg?$_Msg->id:0;
        }else{
            $Message -> get_user = 0;
        }
        if($Message->save()){
            return redirect('admin/message')->with('success','发布成功');
        }else{
            return redirect()->back()->with('fail','发布失败');
        }
    }

    //展示功能
    public function Post(){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $forms = Formitem::where('parent',0)->get();
        return view('admin.post',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "forms"=>$forms,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function PostSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $this->strip_html_tags(array("div","a"),$data["content"]);
        $Post->cover = $data["cover"];
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = $data["level"];
        $Post->author = $data["author"];
        $Post->user_id = $data["user_id"];
        $Post->status = $data["status"];

        if($Post->save()){
            if($data["video"]){
                $this->metaSave($Post->id,'video',$data["video"],isset($meta)&&isset($meta['video'])?$meta['video']:null);
            }else if(isset($meta)&&isset($meta['video'])){
                $this->metaSave($Post->id,'video','',$meta['video'],true);
            }

            if(isset($meta)&&isset($meta['active'])&&$data["active"]!='no'){
                $key = [];
                $value = [];
                $arr = (object)[];
                $i = 0;
                while (isset($data['activeKey_'.$i])){
                    array_push($key,$data['activeKey_'.$i]);
                    array_push($value,$data['activeValue_'.$i]);
                    $i++;
                }
                $arr->key = $key;
                $arr->value = $value;
                $this->metaSave($Post->id,'active',json_encode($arr, JSON_UNESCAPED_UNICODE),isset($meta)&&isset($meta['active'])?$meta['active']:null);
            }else if(isset($meta)&&isset($meta['active'])){
                $this->metaSave($Post->id,'active','',$meta['active'],true);
            }

            if(isset($meta)&&isset($meta['form'])&&$data["form"]!='no'){
                if($data["form"]=='0'){
                    $value = [];
                    $arr = (object)[];
                    $i = 0;
                    while (isset($data['form_'.$i])){
                        array_push($value,$data['form_'.$i]);
                        $i++;
                    }
                    $arr->item = $value;
                    $arr->more = 0;

                    $FormItem = new Formitem();
                    $FormItem->name = '自定义';
                    $FormItem->value = json_encode($arr, JSON_UNESCAPED_UNICODE);
                    $FormItem->parent = $Post->id;
                    $FormItem->save();

                    $this->metaSave($Post->id,'form',$FormItem->id,isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }else{
                    $this->metaSave($Post->id,'form',$data["form"],isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }
            }else if(isset($meta)&&isset($meta['form'])){
                $this->metaSave($Post->id,'form','',$meta['form'],true);
            }

            if(isset($data["timeStatus"])){
                $this->metaSave($Post->id,'activeTime',$data["time"],isset($meta)&&isset($meta['activeTime'])?$meta['activeTime']:null);
            }else if(isset($meta)&&isset($meta['activeTime'])){
                $this->metaSave($Post->id,'activeTime','',$meta['activeTime'],true);
            }
            if($data["toUrl"]){
                $this->metaSave($Post->id,'toUrl',$data["toUrl"],isset($meta)&&isset($meta['toUrl'])?$meta['toUrl']:null);
            }else if(isset($meta)&&isset($meta['toUrl'])){
                $this->metaSave($Post->id,'toUrl','',$meta['toUrl'],true);
            }

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }
            return redirect('admin/post/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function PostEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $tagGroup = TagGroup::where('post_id',$id)->get();
        $forms = Formitem::whereRaw('parent = ? OR parent = ?',[0,$id])->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        return view('admin.post',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "tagGroup"=>json_encode($group),
            "forms"=>$forms,
            "Post"=>$Post,
            "meta"=>$meta,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Posts(Request $request){
        $input = $request->input();
        $TagNum = Tag::where("type","xcx")->where("name","主页")->first();
        $Posts = Post::where("xcx",$TagNum->id);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->tag);
            $Post->tagName = $tag?$tag->name:"已删除";
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","page")->get();
        return view('admin.posts',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function PostDel($id){
        $Post = Post::find($id);
        if($Post->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }

    //用户功能
    public function UserAdd(){
        return view('admin.user',[
            "User"=>null,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserSave(Request $request){
        $data = $request->input('User');
        if(isset($data["id"])){
            $User = User::find($data["id"]);
            if($User->email != $data["email"]){
                $validator = Validator::make($data,[
                    'name' => 'required|max:255',
                    'email' => 'required|email|max:255|unique:users',
                ]);
            }else{
                $validator = Validator::make($data,[
                    'name' => 'required|max:255',
                ]);
            }
        }else{
            $validator = Validator::make($data,[
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|min:6',
            ]);
        }

        if($validator->fails()){
            return redirect()->back()->withErrors($validator)->withInput();
        }

        if(isset($data["id"])){
            $User->name = $data["name"];
            if($User->email != $data["email"])$User->email = $data["email"];
            $User->phone = $data["phone"];
            $User->real_name = $data["real_name"];
            $User->company = $data["company"];
            $User->content = $data["content"];
            if($data["password"])$User->password = bcrypt($data['password']);
            $User->level = $data['level'];

            if($User->save()){
                return redirect()->back()->with('success','修改用户成功');
            }else{
                return redirect()->back()->with('fail','修改用户失败')->withInput();
            }
        }else{
            $User = new User();
            $User->name = $data["name"];
            $User->email = $data["email"];
            $User->phone = $data["phone"];
            $User->password = bcrypt($data['password']);
            $User->level = $data['level'];
            $User->real_name = $data["real_name"];
            $User->company = $data["company"];
            $User->content = $data["content"];

            if($User->save()){
                $UserMeta =  new Usermeta();
                $UserMeta->user_id = $User->id;
                $UserMeta->key = 'avatar';
                $UserMeta->value = 'https://sichuangyi.demopp.in/upload/avatar/avatar.png';
                $UserMeta->save();
                return redirect("/admin/users")->with('success','添加用户成功');
            }else{
                return redirect()->back()->with('fail','添加用户失败')->withInput();
            }
        }
    }
    public function Users(Request $request){
        $input = $request->input();
        $Users = User::orderBy('id', 'desc');
        if($request->has("s")){
            $Users = $Users->where("name","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Users = $Users->where("level",$input["cat"]);
        }
        if($request->has('start')&&$request->has('end')){
            $start_date = date('d-m-Y', strtotime($input["start"]));
            $end_date = date('d-m-Y', strtotime($input["end"]." +1 day"));
            $str_start_date = date("Y-m-d H:i:s",strtotime($start_date));
            $str_end_date = date("Y-m-d H:i:s",strtotime($end_date));
            $Users = $Users->where('created_at','>=',"$str_start_date")->where('created_at','<=',"$str_end_date")->get();
        }else{
            $Users = $Users->paginate(20);
        }
        $ActiveOne = Tag::where('type','xcx')->where('name','路演')->first();
        $ActiveTwo = Tag::where('type','xcx')->where('name','活动')->first();
        foreach ($Users as $user){
            $user->num  = Post::where("user_id",$user->id)->where(function($query) use ($ActiveOne,$ActiveTwo) {
                $query->where('xcx', $ActiveOne->id)
                    ->orWhere(function ($query) use ($ActiveTwo) {
                        $query->where('xcx', $ActiveTwo->id);
                    });
            })->count();
        }
        return view("admin.users",[
            "Users"=>$Users,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserEdit($id){
        $User = User::find($id);
        return view("admin.user",[
            "User"=>$User,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserProfile(){
        $User = User::find(Auth::user()->id);
        return view("admin.user",[
            "User"=>$User,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserDel($id){
        $User = User::find($id);
        if($User->delete()){
            return redirect('admin/users')->with('success','删除成功');
        }else{
            return redirect('admin/users')->with('fail','删除失败');
        }
    }
    public function wx(){
        return view("auth.wx");
    }

    //服务大厅
    public function Services(Request $request){
        $input = $request->input();
        $TagNum = Tag::where('type','xcx')->where('name','服务')->first();
        $Posts = Post::where('xcx',$TagNum->id);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->tag);
            $Post->tagName = $tag?$tag->name:"已删除";
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","service")->get();
        return view('admin.services',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Service(){
        $xcxs = Tag::where('type','xcx')->get();
        $services = Tag::where('type','service')->get();
        $tags = Tag::where('type','tag')->get();
        $forms = Formitem::where('parent',0)->get();
        $filter = Array('id'=>[],'name'=>[],'tag'=>[],'filterName'=>[]);
        foreach ($services as $s){
            $t_arr = Tag::where("parent_id",$s->id)->get();
            $_id = [];
            $_name = [];
            foreach ($t_arr as $_t){
                array_push($_id,$_t->id);
                array_push($_name,$_t->name);
            }
            array_push($filter['id'],$_id);
            array_push($filter['name'],$_name);
            array_push($filter['tag'],$s->id);
            array_push($filter['filterName'],$s->filter);
        }
        return view('admin.service',[
            "xcxs"=>$xcxs,
            "services"=>$services,
            "tags"=>$tags,
            "forms"=>$forms,
            "filter"=>json_encode($filter),
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ServiceSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
            if(isset($data["created_at"]))$Post->created_at = $data["created_at"];
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $data["content"];
        $Post->cover = $data["cover"];
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = $data["level"];
        $Post->author = $data["author"];
        $Post->user_id = $data["user_id"];
        $Post->status = $data["status"];

        if($Post->save()){
            if($data["video"]){
                $this->metaSave($Post->id,'video',$data["video"],isset($meta)&&isset($meta['video'])?$meta['video']:null);
            }else if(isset($meta)&&isset($meta['video'])){
                $this->metaSave($Post->id,'video','',$meta['video'],true);
            }
            if(isset($data["activeKey_0"])){
                $key = [];
                $value = [];
                $arr = (object)[];
                $i = 0;
                while (isset($data['activeKey_'.$i])){
                    array_push($key,$data['activeKey_'.$i]);
                    array_push($value,$data['activeValue_'.$i]);
                    $i++;
                }
                $arr->key = $key;
                $arr->value = $value;
                $this->metaSave($Post->id,'service',json_encode($arr, JSON_UNESCAPED_UNICODE),isset($meta)&&isset($meta['service'])?$meta['service']:null);
            }else if(isset($meta)&&isset($meta['service'])){
                $this->metaSave($Post->id,'service','',$meta['service'],true);
            }

            if($data["form"]!='no'){
                if($data["form"]=='0'){
                    $value = [];
                    $arr = (object)[];
                    $i = 0;
                    while (isset($data['form_'.$i])){
                        array_push($value,$data['form_'.$i]);
                        $i++;
                    }
                    $arr->item = $value;
                    $arr->more = 0;

                    $FormItem = new Formitem();
                    $FormItem->name = '自定义';
                    $FormItem->value = json_encode($arr, JSON_UNESCAPED_UNICODE);
                    $FormItem->parent = $Post->id;
                    $FormItem->save();

                    $this->metaSave($Post->id,'form',$FormItem->id,isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }else{
                    $this->metaSave($Post->id,'form',$data["form"],isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }
            }else if(isset($meta)&&isset($meta['form'])){
                $this->metaSave($Post->id,'form','',$meta['form'],true);
            }

            if(isset($data["subtitle"])){
                $this->metaSave($Post->id,'subtitle',$data["subtitle"],isset($meta)&&isset($meta['subtitle'])?$meta['subtitle']:null);
            }else if(isset($meta)&&isset($meta['subtitle'])){
                $this->metaSave($Post->id,'subtitle','',$meta['subtitle'],true);
            }

            if(isset($data["summary"])){
                $this->metaSave($Post->id,'summary',$data["summary"],isset($meta)&&isset($meta['summary'])?$meta['summary']:null);
            }else if(isset($meta)&&isset($meta['summary'])){
                $this->metaSave($Post->id,'summary','',$meta['summary'],true);
            }

            if(isset($data["price"])){
                $this->metaSave($Post->id,'price',$data["price"],isset($meta)&&isset($meta['price'])?$meta['price']:null);
            }else if(isset($meta)&&isset($meta['price'])){
                $this->metaSave($Post->id,'price',0,$meta['price']);
            }
            if($data["viewQR"]){
                $this->metaSave($Post->id,'viewQR',$data["viewQR"],isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
            }else{
                if(isset($data["createQR"])&&$data["createQR"]=='on'){
                    $QR = $this->getQR($Post->id,'pages/view/view?id='.$Post->id.'&&type=service');
                    if($QR){
                        $this->metaSave($Post->id,'viewQR',$QR,isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
                    }
                }else if(isset($meta)&&isset($meta['viewQR'])){
                    $this->metaSave($Post->id,'viewQR','',$meta['viewQR'],true);
                }
            }


            $this->metaSave($Post->id,'startService',$data["startService"],isset($meta)&&isset($meta['startService'])?$meta['startService']:null);
            $this->metaSave($Post->id,'endService',$data["endService"],isset($meta)&&isset($meta['endService'])?$meta['endService']:null);
            $this->metaSave($Post->id,'btn',$data["btn"],isset($meta)&&isset($meta['btn'])?$meta['btn']:null);
            $this->metaSave($Post->id,'servicePhone',$data["servicePhone"],isset($meta)&&isset($meta['servicePhone'])?$meta['servicePhone']:null);
            $this->metaSave($Post->id,'smsPhone',$data["smsPhone"],isset($meta)&&isset($meta['smsPhone'])?$meta['smsPhone']:null);
            $this->metaSave($Post->id,'admin',$data["admin"],isset($meta)&&isset($meta['admin'])?$meta['admin']:null);

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }

            if($data["phone"]){
                $feiyuApi = new FeiyuApi();
                $ret = $feiyuApi->getAccountUrlAction('86'.$data["phone"]);
                if($ret["resultCode"]==0){
                    $f = $ret["result"]["fyAccountId"];
                    $this->metaSave($Post->id,'fy',$f,isset($meta)&&isset($meta['fy'])?$meta['fy']:null);
                    $this->metaSave($Post->id,'phone',$data["phone"],isset($meta)&&isset($meta['phone'])?$meta['phone']:null);
                }else{
                    $p = Postmeta::where("post_id",$Post->id)->where("key","phone")->first();
                    if($p&&$p->value){
                        $count = Postmeta::where("key","phone")->where("value",$p->value)->count();
                        if($count==1){
                            $ret = $feiyuApi->getAccountUrlAction('86'.$p->value);
                            if($ret["resultCode"]==0){
                                $f = $ret["result"]["fyAccountId"];
                                $ret = $feiyuApi->modifyAccountDisplayNumberAction($f,'86'.$data["phone"]);
                                if($ret["resultCode"]==0){
                                    $this->metaSave($Post->id,'fy',$f,isset($meta)&&isset($meta['fy'])?$meta['fy']:null);
                                    $this->metaSave($Post->id,'phone',$data["phone"],isset($meta)&&isset($meta['phone'])?$meta['phone']:null);
                                    return redirect('admin/service/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
                                }
                            }
                        }
                    }

                    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                    $charactersLength = strlen($characters);
                    $randomString = '';
                    for ($i = 0; $i < 8; $i++) {
                        $randomString .= $characters[rand(0, $charactersLength - 1)];
                    }
                    $ret = $feiyuApi->addAccountUrlAction($randomString,'86'.$data["phone"]);
                    if($ret["resultCode"]==0){
                        $this->metaSave($Post->id,'fy',$ret["result"]["fyAccountId"],isset($meta)&&isset($meta['fy'])?$meta['fy']:null);
                        $this->metaSave($Post->id,'phone',$data["phone"],isset($meta)&&isset($meta['phone'])?$meta['phone']:null);
                    }else{
                        return redirect('admin/service/edit/'.$Post->id)->with('fail',$ret["resultMsg"]);
                    }
                }
            }else if(isset($meta)&&isset($meta['phone'])){
                $this->metaSave($Post->id,'phone','',$meta['phone']);
                $this->metaSave($Post->id,'fy','',$meta['fy']);
            }
            return redirect('admin/service/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function ServiceEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $services= Tag::where('type','service')->get();
        $tags = Tag::where('type','tag')->get();
        $tagGroup = TagGroup::where('post_id',$id)->get();
        $forms = Formitem::whereRaw('parent = ? OR parent = ?',[0,$id])->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        $filter = Array('id'=>[],'name'=>[],'tag'=>[],'filterName'=>[]);
        foreach ($services as $s){
            $t_arr = Tag::where("parent_id",$s->id)->get();
            $_id = [];
            $_name = [];
            foreach ($t_arr as $_t){
                array_push($_id,$_t->id);
                array_push($_name,$_t->name);
            }
            array_push($filter['id'],$_id);
            array_push($filter['name'],$_name);
            array_push($filter['tag'],$s->id);
            array_push($filter['filterName'],$s->filter);
        }
        return view('admin.service',[
            "xcxs"=>$xcxs,
            "services"=>$services,
            "tags"=>$tags,
            "tagGroup"=>json_encode($group),
            "forms"=>$forms,
            "Post"=>$Post,
            "meta"=>$meta,
            "filter"=>json_encode($filter),
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }

    //活动路演
    public function Actives(Request $request){
        $input = $request->input();
//        $ActiveOne = Tag::where('type','xcx')->where('name','路演')->first();
        $ActiveTwo = Tag::where('type','xcx')->where('name','活动')->first();
        $ActiveThree = Tag::where('type','xcx')->where('name','回顾')->first();
        $Posts = Post::whereIn("xcx",[$ActiveTwo->id,$ActiveThree->id]);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        $status = Array("待审","通过","拒绝");
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->xcx);
            $Post->tagName = $tag?$tag->name:"已删除";
            $Post->statusName = $status[$Post->status];
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","page")->get();
        return view('admin.actives',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "show"=>0,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Active(){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $forms = Formitem::where('parent',0)->get();
        return view('admin.active',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "forms"=>$forms,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ActiveSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $data["content"];
        $Post->cover = $data["cover"];
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = $data["level"];
        $Post->author = $data["author"];
        $Post->status = $data["status"];
        $Post->user_id = $data["user_id"];

        if($Post->save()){
            if($data["video"]){
                $this->metaSave($Post->id,'video',$data["video"],isset($meta)&&isset($meta['video'])?$meta['video']:null);
            }else if(isset($meta)&&isset($meta['video'])){
                $this->metaSave($Post->id,'video','',$meta['video'],true);
            }
            if($data["mapImage"]){
                $this->metaSave($Post->id,'map',$data["mapImage"],isset($meta)&&isset($meta['mapImage'])?$meta['mapImage']:null);
            }else if(isset($meta)&&isset($meta['mapImage'])){
                $this->metaSave($Post->id,'mapImage','',$meta['mapImage'],true);
            }
            if($data["showLevel"]!=''){
                $this->metaSave($Post->id,'showLevel',$data["showLevel"],isset($meta)&&isset($meta['showLevel'])?$meta['showLevel']:null);
            }else if(isset($meta)&&isset($meta['showLevel'])){
                $this->metaSave($Post->id,'showLevel','',$meta['showLevel'],true);
            }
            if($data["viewQR"]){
                $this->metaSave($Post->id,'viewQR',$data["viewQR"],isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
            }else{
                if(isset($data["createQR"])&&$data["createQR"]=='on'){
                    $QR = $this->getQR($Post->id,'pages/view/view?id='.$Post->id.'&&type='.($Post->xcx==3?'active&show=1':'active'));
                    if($QR){
                        $this->metaSave($Post->id,'viewQR',$QR,isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
                    }
                }else if(isset($meta)&&isset($meta['viewQR'])){
                    $this->metaSave($Post->id,'viewQR','',$meta['viewQR'],true);
                }
            }

            if($data["form"]!='no'){
                $this->metaSave($Post->id,'form',$data["form"],isset($meta)&&isset($meta['form'])?$meta['form']:null);
            }else if(isset($meta)&&isset($meta['form'])){
                $this->metaSave($Post->id,'form','',$meta['form'],true);
            }

            $this->metaSave($Post->id,'activeTime',$data["time"],isset($meta)&&isset($meta['activeTime'])?$meta['activeTime']:null);
            $this->metaSave($Post->id,'endTime',$data["endTime"],isset($meta)&&isset($meta['endTime'])?$meta['endTime']:null);
            $this->metaSave($Post->id,'city',$data["city"],isset($meta)&&isset($meta['city'])?$meta['city']:null);
            $this->metaSave($Post->id,'area',$data["area"],isset($meta)&&isset($meta['area'])?$meta['area']:null);
            $this->metaSave($Post->id,'address',$data["address"],isset($meta)&&isset($meta['address'])?$meta['address']:null);
            $this->metaSave($Post->id,'latitude',$data["latitude"],isset($meta)&&isset($meta['latitude'])?$meta['latitude']:null);
            $this->metaSave($Post->id,'longitude',$data["longitude"],isset($meta)&&isset($meta['longitude'])?$meta['longitude']:null);
            $this->metaSave($Post->id,'peoples',$data["peoples"],isset($meta)&&isset($meta['peoples'])?$meta['peoples']:null);
            $this->metaSave($Post->id,'price',$data["price"],isset($meta)&&isset($meta['price'])?$meta['price']:null);
            $this->metaSave($Post->id,'organizers',$data["organizers"],isset($meta)&&isset($meta['organizers'])?$meta['organizers']:null);
            $this->metaSave($Post->id,'btn',$data["btn"],isset($meta)&&isset($meta['btn'])?$meta['btn']:null);

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }
            return redirect('admin/active/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function ActiveEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $tagGroup = TagGroup::where('post_id',$id)->get();
        $forms = Formitem::whereRaw('parent = ? OR parent = ?',[0,$id])->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        return view('admin.active',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "tagGroup"=>json_encode($group),
            "forms"=>$forms,
            "Post"=>$Post,
            "meta"=>$meta,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Shows(Request $request){
        $input = $request->input();
        $ActiveOne = Tag::where('type','xcx')->where('name','路演')->first();
        $Posts = Post::where("xcx",$ActiveOne->id);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        $status = Array("待审","通过","拒绝");
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->xcx);
            $Post->tagName = $tag?$tag->name:"已删除";
            $Post->statusName = $status[$Post->status];
            $meta = Postmeta::where("post_id",$Post->id)->where("key","showStatus")->first();
            $Post->showStatus = $meta?$meta->value:'';
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","page")->get();
        return view('admin.actives',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "show"=>1,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShowStatus($id){
        $meta = Postmeta::where("post_id",$id)->where("key","showStatus")->first();
        if($meta){
            $meta->value = $meta->value==1?2:1;
        }else{
            $meta = new Postmeta();
            $meta->post_id = $id;
            $meta->key = "showStatus";
            $meta->value = 1;
        }
        if($meta->save()){
            return redirect()->back()->with('success','修改成功');
        }else{
            return redirect()->back()->with('fail','修改失败');
        }
    }
    public function ShowsUser($id){
        $Users = LiveUser::where("parent_id",$id)->orderBy("id","desc")->paginate(50);
        foreach ($Users as $u){
            $user = User::select("name")->find($u->user_id);
            if($user){
                $u->name = $user->name;
                $u->count = Live::where("parent_id",$id)->where("user_id",$u->user_id)->count();
            }else{
                $u->name = '用户已删除';
                $u->count = 0;
            }
        }
        return view('admin.showUser',[
            "LiveId"=>$id,
            "Users"=>$Users,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShowsUserAdd(Request $request){
        $input = $request->input();
        $user = LiveUser::where("parent_id",$input["id"])->where("user_id",$input["uid"])->first();
        if(!$user){
            $user = new LiveUser();
            $user->parent_id = $input["id"];
            $user->user_id = $input["uid"];
            if($user->save()){
                return redirect()->back()->with('success','添加成功');
            }else{
                return redirect()->back()->with('fail','添加失败');
            }
        }else{
            return redirect()->back()->with('fail','用户已存在');
        }

    }
    public function ShowsLive($id){
        $Lives = Live::select("id","user_id","type","content","created_at")->where("parent_id",$id)->orderBy("id","desc")->paginate(50);
        foreach ($Lives as $live){
            $user = User::select("name")->find($live->user_id);
            $live->name = $user?$user->name:'用户已删除';
        }
        return view('admin.showLive',[
            "Lives"=>$Lives,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShowsLiveDel($id){
        $live = Live::find($id);
        if($live&&$live->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }

    //商铺功能
    public function Shops(Request $request){
        $input = $request->input();
        $Shops = ShopUser::where('status','<',2)->orderBy('id', 'desc');
        if($request->has("s")){
            $Shops = $Shops->where("name","like","%".$input["s"]."%");
        }
        $Shops = $Shops->paginate(20);
        foreach ($Shops as $s) {
            $user = User::find($s->user_id);
            $s->user = $user?$user->name:"0";
        }
        return view('admin.shops',[
            "Shops"=>$Shops,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Shop(){
        return view('admin.shop',[
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = ShopUser::find($data["id"]);
            $Postmeta = Shopmeta::where('shop_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
            if(isset($data["created_at"]))$Post->created_at = $data["created_at"];
        }else{
            $Post = new ShopUser();
        }

        $Post->name = $data["name"];
        $Post->content = $data["content"];
        $Post->cover = $data["cover"];
        $Post->summary = $data["summary"];
        $Post->address = $data["address"];
        $Post->user_id = (int)$data["user_id"]?$data["user_id"]:1;
        $Post->phone = $data["phone"];
        $Post->status = $data["status"];

        if($Post->save()){
            if($data["viewQR"]){
                $this->ShopMetaSave($Post->id,'viewQR',$data["viewQR"],isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
            }else{
                if(isset($data["createQR"])&&$data["createQR"]=='on'){
                    $QR = $this->getQR($Post->id,'pages/shop/shop?id='.$Post->id);
                    if($QR){
                        $this->ShopMetaSave($Post->id,'viewQR',$QR,isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
                    }
                }else if(isset($meta)&&isset($meta['viewQR'])){
                    $this->ShopMetaSave($Post->id,'viewQR','',$meta['viewQR'],true);
                }
            }
            if(isset($data["coupon_use_limit"])){
                $this->ShopMetaSave($Post->id,'coupon_use_limit',$data["coupon_use_limit"],isset($meta)&&isset($meta['coupon_use_limit'])?$meta['coupon_use_limit']:null);
            }else if(isset($meta)&&isset($meta['coupon_use_limit'])){
                $this->ShopMetaSave($Post->id,'coupon_use_limit','',$meta['coupon_use_limit'],true);
            }

            $this->ShopMetaSave($Post->id,'startService',$data["startService"],isset($meta)&&isset($meta['startService'])?$meta['startService']:null);
            $this->ShopMetaSave($Post->id,'endService',$data["endService"],isset($meta)&&isset($meta['endService'])?$meta['endService']:null);
            $this->ShopMetaSave($Post->id,'delivery',$data["delivery"],isset($meta)&&isset($meta['delivery'])?$meta['delivery']:null);
            $this->ShopMetaSave($Post->id,'discount_full',$data["discount_full"],isset($meta)&&isset($meta['discount_full'])?$meta['discount_full']:null);
            $this->ShopMetaSave($Post->id,'discount_cut',$data["discount_cut"],isset($meta)&&isset($meta['discount_cut'])?$meta['discount_cut']:null);
            $this->ShopMetaSave($Post->id,'active',$data["active"],isset($meta)&&isset($meta['active'])?$meta['active']:null);

            return redirect('admin/shops/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function ShopEdit($id){
        $Post = ShopUser::find($id);
        $Postmeta = Shopmeta::where('shop_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        return view('admin.shop',[
            "Post"=>$Post,
            "meta"=>$meta,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopDel($id){
        $Shop = ShopUser::find($id);
        $Shop->status = 9;
        if($Shop->save()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function ShopsCat(Request $request){
        $input = $request->input();
        $Cats = ShopCat::orderBy('id', 'desc');
        if($request->has("shop")){
            $Cats = $Cats->where('parent_id',$input["shop"]);
            $Shops = ShopUser::find($input["shop"]);
        }else{
            $Shops = ShopUser::get();
        }
        $Cats = $Cats->paginate(20);
        if($request->has("shop")){
            foreach ($Cats as $cat){
                $cat->shop = $Shops?$Shops->name:'暂无';
            }
        }else{
            foreach ($Cats as $cat){
                $Shop = ShopUser::find($cat->parent_id);
                $cat->shop = $Shop?$Shop->name:'暂无';
            }
        }
        return view('admin.shopCats',[
            "Cats"=>$Cats,
            "Shops"=>$Shops,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopsCatSave(Request $request){
        $data = $request->input('Cat');
        if(isset($data['id'])){
            $Cat = ShopCat::find($data['id']);
            $Cat->name = $data["name"];
            $Cat->order_id = $data["order_id"];
            if($Cat->save()){
                return redirect()->back()->with('success','更新成功');
            }else{
                return redirect()->back()->with('fail','更新失败');
            }
        }else{
            $Cat = new ShopCat();

            $Cat->name = $data["name"];
            $Cat->parent_id = $data["parent_id"];
            if($data["order_id"]){
                $Cat->order_id = $data["order_id"];
            }else{
                $num = ShopCat::where('parent_id',$data["parent_id"])->count();
                $Cat->order_id = $num+1;
            }

            if($Cat->save()){
                return redirect()->back()->with('success','新增成功');
            }else{
                return redirect()->back()->with('fail','新增失败');
            }
        }
    }
    public function ShopsCatEdit($id){
        $Cat = ShopCat::find($id);
        return view('admin.shopCatEdit',[
            "Cat"=>$Cat,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopCatDel($id){
        $Shop = ShopCat::find($id);
        if($Shop->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function ShopGoods(Request $request){
        $input = $request->input();
        $Goods = ShopGoods::where('status','<',2)->orderBy('created_at', 'desc');
        if($request->has("shop")){
            $Goods = $Goods->where('parent_id',$input["shop"]);
            $Shops = ShopUser::find($input["shop"]);
        }else{
            $Shops = ShopUser::where('status','<',2)->get();
        }
        if($request->has("s")){
            $Goods = $Goods->where("name","like","%".$input["s"]."%")->paginate(100);
        }else{
            $Goods = $Goods->paginate(20);
        }
        if($request->has("shop")){
            foreach ($Goods as $g){
                $g->shop = $Shops?$Shops->name:'暂无';
                $catName = ShopCat::find($g->cat);
                $g->catName = $catName?$catName->name:"";
            }
        }else{
            foreach ($Goods as $g){
                $Shop = ShopUser::find($g->parent_id);
                $g->shop = $Shop?$Shop->name:'暂无';
                $catName = ShopCat::find($g->cat);
                $g->catName = $catName?$catName->name:"";
            }
        }
        return view('admin.goods',[
            "Goods"=>$Goods,
            "Shops"=>$Shops,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopGoodsAdd($id){
        $Cats = ShopCat::where('parent_id',$id)->get();
        return view('admin.goodsEdit',[
            "Cats"=>$Cats,
            "parent_id"=>$id,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopsGoodsSave(Request $request){
        $data = $request->input('Goods');
        if(isset($data['id'])){
            $Goods = ShopGoods::find($data['id']);
        }else{
            $Goods = new ShopGoods();
            $Goods->parent_id = $data["parent_id"];
        }

        $Goods->name = $data["name"];
        $Goods->price = $data["price"]?$data["price"]:0;
        $Goods->status = $data["status"];
        $Goods->more = $data["more"];
        $Goods->cat = $data["cat"];
        $Goods->kind = isset($data["kind"])?$data["kind"]:'';
        if(isset($data["created_at"])&&$data["created_at"])$Goods->created_at = $data["created_at"];
        if($Goods->save()){
            return redirect('admin/goods/edit/'.$Goods->id)->with('success',isset($data['id'])?'更新成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($data['id'])?'更新失败':'新增失败');
        }
    }
    public function ShopGoodsEdit($id){
        $Goods = ShopGoods::find($id);
        $Cats = ShopCat::where('parent_id',$Goods->parent_id)->get();
        return view('admin.goodsEdit',[
            "Goods"=>$Goods,
            "Cats"=>$Cats,
            "parent_id"=>$Goods->parent_id,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopDelEdit($id){
        $Goods = ShopGoods::find($id);
        $Goods->status = 9;
        if($Goods->save()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function ShopCoupons(Request $request){
        $input = $request->input();
        $TagNum = Tag::where('type','xcx')->where('name','优惠券')->first();
        $Posts = Post::where('xcx',$TagNum->id)->where('status','<',2);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->tag);
            $couponNum = Postmeta::where("post_id",$Post->id)->where("key","coupon_num")->first();
            $Post->tagName = $tag?$tag->name:"已删除";
            $Post->couponNum = $couponNum?$couponNum->value:"0";
        }
        $Cats = Tag::where("type","couponCat")->get();
        return view('admin.coupons',[
            "Posts"=>$Posts,
            "Cats"=>$Cats,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopCoupon(){
        $xcxs = Tag::where('type','xcx')->get();
        $services = Tag::where('type','couponCat')->get();
        $filter = Array('id'=>[],'name'=>[],'tag'=>[],'filterName'=>[]);
        foreach ($services as $s){
            $t_arr = Tag::where("parent_id",$s->id)->get();
            $_id = [];
            $_name = [];
            foreach ($t_arr as $_t){
                array_push($_id,$_t->id);
                array_push($_name,$_t->name);
            }
            array_push($filter['id'],$_id);
            array_push($filter['name'],$_name);
            array_push($filter['tag'],$s->id);
            array_push($filter['filterName'],$s->filter);
        }
        return view('admin.coupon',[
            "xcxs"=>$xcxs,
            "services"=>$services,
            "filter"=>json_encode($filter),
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopCouponSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
            if(isset($data["created_at"]))$Post->created_at = $data["created_at"];
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $data["content"];
        $Post->cover = '';
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = 0;
        $Post->author = $data["author"];
        $Post->user_id = $data["user_id"];
        $Post->status = $data["status"];

        if($Post->save()){
            $coupon_type = $data["coupon_id"]==0?'all':$data["coupon_type"];
            if(isset($data["activeKey_0"])){
                $key = [];
                $value = [];
                $arr = (object)[];
                $i = 0;
                while (isset($data['activeKey_'.$i])){
                    array_push($key,$data['activeKey_'.$i]);
                    array_push($value,$data['activeValue_'.$i]);
                    $i++;
                }
                $arr->key = $key;
                $arr->value = $value;
                $this->metaSave($Post->id,'service',json_encode($arr, JSON_UNESCAPED_UNICODE),isset($meta)&&isset($meta['service'])?$meta['service']:null);
            }else if(isset($meta)&&isset($meta['service'])){
                $this->metaSave($Post->id,'service','',$meta['service'],true);
            }
            if($data["viewQR"]){
                $this->metaSave($Post->id,'viewQR',$data["viewQR"],isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
            }else{
                if(isset($data["createQR"])&&$data["createQR"]=='on'){
                    $QR = $this->getQR($Post->id,'pages/view/view?id='.$Post->id.'&&type=coupon');
                    if($QR){
                        $this->metaSave($Post->id,'viewQR',$QR,isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
                    }
                }else if(isset($meta)&&isset($meta['viewQR'])){
                    $this->metaSave($Post->id,'viewQR','',$meta['viewQR'],true);
                }
            }
            if(isset($data["coupon_discount"])){
                $this->metaSave($Post->id,'coupon_discount',$data["coupon_discount"],isset($meta)&&isset($meta['coupon_discount'])?$meta['coupon_discount']:null);
            }else if(isset($meta)&&isset($meta['coupon_discount'])){
                $this->metaSave($Post->id,'coupon_discount','',$meta['coupon_discount'],true);
            }
            if(isset($data["coupon_cash"])){
                $this->metaSave($Post->id,'coupon_cash',$data["coupon_cash"],isset($meta)&&isset($meta['coupon_cash'])?$meta['coupon_cash']:null);
            }else if(isset($meta)&&isset($meta['coupon_cash'])){
                $this->metaSave($Post->id,'coupon_cash','',$meta['coupon_cash'],true);
            }
            if(isset($data["coupon_full"])&&isset($data["coupon_cut"])){
                $this->metaSave($Post->id,'coupon_full',$data["coupon_full"],isset($meta)&&isset($meta['coupon_full'])?$meta['coupon_full']:null);
                $this->metaSave($Post->id,'coupon_cut',$data["coupon_cut"],isset($meta)&&isset($meta['coupon_cut'])?$meta['coupon_cut']:null);
            }else if(isset($meta)&&isset($meta['coupon_full'])&&isset($data["coupon_cut"])){
                $this->metaSave($Post->id,'coupon_full','',$meta['coupon_full'],true);
                $this->metaSave($Post->id,'coupon_cut','',$meta['coupon_cut'],true);
            }
            if($data["coupon_price"]){
                $this->metaSave($Post->id,'coupon_price',$data["coupon_price"],isset($meta)&&isset($meta['coupon_price'])?$meta['coupon_price']:null);
            }else if(isset($meta)&&isset($meta['coupon_price'])){
                $this->metaSave($Post->id,'coupon_price','',$meta['coupon_price'],true);
            }
            if($data["coupon_code"]){
                $this->metaSave($Post->id,'coupon_code',$data["coupon_code"],isset($meta)&&isset($meta['coupon_code'])?$meta['coupon_code']:null);
            }else if(isset($meta)&&isset($meta['coupon_code'])){
                $this->metaSave($Post->id,'coupon_code','',$meta['coupon_code'],true);
            }
            if($data["coupon_level"]){
                $this->metaSave($Post->id,'coupon_level',$data["coupon_level"],isset($meta)&&isset($meta['coupon_level'])?$meta['coupon_level']:null);
            }else if(isset($meta)&&isset($meta['coupon_level'])){
                $this->metaSave($Post->id,'coupon_level','',$meta['coupon_level'],true);
            }
            if(isset($data["coupon_form"])){
                $this->metaSave($Post->id,'coupon_form',1,isset($meta)&&isset($meta['coupon_form'])?$meta['coupon_form']:null);
            }else if(isset($meta)&&isset($meta['coupon_form'])){
                $this->metaSave($Post->id,'coupon_form','',$meta['coupon_form'],true);
            }
            if($data["coupon_summary"]){
                $this->metaSave($Post->id,'coupon_summary',$data["coupon_summary"],isset($meta)&&isset($meta['coupon_summary'])?$meta['coupon_summary']:null);
            }else if(isset($meta)&&isset($meta['coupon_summary'])){
                $this->metaSave($Post->id,'coupon_summary','',$meta['coupon_summary'],true);
            }
            $this->metaSave($Post->id,'startCoupon',$data["startCoupon"],isset($meta)&&isset($meta['startCoupon'])?$meta['startCoupon']:null);
            $this->metaSave($Post->id,'endCoupon',$data["endCoupon"],isset($meta)&&isset($meta['endCoupon'])?$meta['endCoupon']:null);
            $this->metaSave($Post->id,'coupon_type',$coupon_type,isset($meta)&&isset($meta['coupon_type'])?$meta['coupon_type']:null);
            $this->metaSave($Post->id,'coupon_id',$data["coupon_id"],isset($meta)&&isset($meta['coupon_id'])?$meta['coupon_id']:null);
            $this->metaSave($Post->id,'coupon_num',$data["coupon_num"],isset($meta)&&isset($meta['coupon_num'])?$meta['coupon_num']:null);
            $this->metaSave($Post->id,'coupon_limit',$data["coupon_limit"],isset($meta)&&isset($meta['coupon_limit'])?$meta['coupon_limit']:null);

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }

            return redirect('admin/coupons/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function ShopCouponEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $services = Tag::where('type','couponCat')->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        $filter = Array('id'=>[],'name'=>[],'tag'=>[],'filterName'=>[]);
        foreach ($services as $s){
            $t_arr = Tag::where("parent_id",$s->id)->get();
            $_id = [];
            $_name = [];
            foreach ($t_arr as $_t){
                array_push($_id,$_t->id);
                array_push($_name,$_t->name);
            }
            array_push($filter['id'],$_id);
            array_push($filter['name'],$_name);
            array_push($filter['tag'],$s->id);
            array_push($filter['filterName'],$s->filter);
        }
        $tagGroup = TagGroup::where('post_id',$id)->get();
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        return view('admin.coupon',[
            "xcxs"=>$xcxs,
            "services"=>$services,
            "tagGroup"=>json_encode($group),
            "Post"=>$Post,
            "meta"=>$meta,
            "filter"=>json_encode($filter),
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ShopCouponDel($id){
        $Post = Post::find($id);
        $Post->status = 9;
        if($Post->save()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function CreateQR(Request $request){
        $data = $request->input('Post');
        if(isset($data["link"])){
            $link = $data["link"];
            $width = $data["width"]?$data["width"]:430;
            $url = $this->getQR(time(),$link,$width);
        }else{
            $width = "";
            $url = "";
            $link = "";
        }
        return view('admin.qr',[
            "width"=>$width,
            "url"=>$url,
            "link"=>$link,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function GetOrder(Request $request){
        $input = $request->input();
        $Orders = ShopOrder::orderBy('id', 'desc');
        if($request->has("status")){
            $Orders = $Orders->where('status',$input["status"]);
        }
        if($request->has("s")){
            $Orders = $Orders->where("trade","like","%".$input["s"]."%");
        }
        if($request->has('start')&&$request->has('end')){
            $start_date = date('d-m-Y', strtotime($input["start"]));
            $end_date = date('d-m-Y', strtotime($input["end"]." +1 day"));
            $str_start_date = date("Y-m-d H:i:s",strtotime($start_date));
            $str_end_date = date("Y-m-d H:i:s",strtotime($end_date));
            $Orders = $Orders->where('created_at','>=',"$str_start_date")->where('created_at','<=',"$str_end_date")->get();
        }else{
            $Orders = $Orders->paginate(20);
        }
//        $Shops = ShopUser::where("status",1)->get();
        foreach ($Orders as $s) {
            $user = User::find($s->user_id);
            $s->user = $user?$user->name:"0";
        }
        return view('admin.orders',[
//            "Shops"=>$Shops,
            "Orders"=>$Orders,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function OrderView($id){
        $Order = ShopOrder::find($id);
        $user = User::find($Order->user_id);
        $Order->user = $user?$user->name:"0";
        $Order->content = json_decode($Order->content);
        return view('admin.ordersView',[
            "CurrentUser"=>$this->CurrentUser(),
            "order"=>$Order
        ]);
    }
    public function ShopCode(Request $request){
        $input = $request->input();
        $Code = ShopCode::orderBy('id', 'desc');
        if($request->has("status")){
            $Code = $Code->where('status',$input["status"]);
        }
        $Code = $Code->paginate(20);
        foreach ($Code as $c) {
            $shop = ShopUser::find($c->shop_id);
            $c->name = $shop?$shop->name:'无此商户';
            $order = ShopOrder::find($c->order_id);
            $c->order = $order?$order->trade:'';
        }
        return view('admin.codes',[
            "CurrentUser"=>$this->CurrentUser(),
            "codes"=>$Code
        ]);
    }
    public function ShopCodeDel($id){
        $Code = ShopCode::find($id);
        if($Code->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }


}
